const Router=require('koa-router');
const login=new Router(); 
const sqldata=require('../sqldata')
//获得管理员名单
login.get('/', async (ctx)=>{
    let val=ctx.request.query;
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `select * from login`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    ctx.body = JSON.stringify(mydata);
})
//验证管理员
login.post('/', async (ctx,next)=>{
    let val=ctx.request.body;
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `select * from login where username='${val.username}' and password='${val.password}'`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            console.log('return',data)
            resolve(data);	
        })
    })
    ctx.response.status=200
    if(mydata.length>0){
        console.log(mydata)
        ctx.body=JSON.stringify(mydata);
    }
    
})
//添加管理员
login.post('/addUser', async (ctx)=>{
    let val=ctx.request.body;
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `insert into login (username,password) values('${val.username}','${val.password}')`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    ctx.body=JSON.stringify('添加成功')
})
//删除管理员
login.delete('/delUser', async (ctx)=>{
    let val=JSON.parse(ctx.request.body);
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `delete from login where username='${val.username}'`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    ctx.body=JSON.stringify('删除成功')
})

module.exports=login;